package com.wspyydshhh.mytool.slice;

import com.wspyydshhh.mytool.ResourceTable;
import com.wspyydshhh.mytool.pojo.ConstData;
import com.wspyydshhh.mytool.util.DBUtil;
import com.wspyydshhh.mytool.util.DataUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.DependentLayout;
import ohos.data.distributed.common.ChangeNotification;
import ohos.data.distributed.common.KvStoreObserver;
import ohos.data.distributed.common.SubscribeType;
import ohos.data.distributed.user.SingleKvStore;

public class MainAbilitySlice extends AbilitySlice {
    private Component component;
    private DependentLayout dependentLayout;
    private final DataUtil dataUtil = new DataUtil();
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        component = findComponentById(ResourceTable.Id_add);

        component.setClickedListener(this::onClick);
        //获取数据库
        SingleKvStore singleKvStore = DBUtil.initOrGetDB(this, ConstData.dataBaseId);
        singleKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL, new KvStoreObserver() {
            //通过子线程更新数据
            @Override
            public void onChange(ChangeNotification changeNotification) {
                //更新数据到list
                getUITaskDispatcher().asyncDispatch(() -> dataUtil.updataList(singleKvStore));
            }
        });
    }

    public void onClick(Component component) {
        Intent intent = new Intent();
        Operation addAbility = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName("com.wspyydshhh.mytool")
                .withAbilityName("AddAbility")
                .build();
        intent.setOperation(addAbility);
        startAbility(intent);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
